package github.ziwukun.jsonql.orm;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.core.util.StrUtil;
import github.ziwukun.jsonql.lang.CmpOpr;
import github.ziwukun.jsonql.utils.CollectionUtils;


/**
 * 链接属性实现
 * @author Hugo.Yu
 */
class JoinPropImpl implements JoinProp{
	private static final long serialVersionUID = 9023901245300147775L;
	String propName;
	boolean single;
	Set<SupportCondition> supportConditions = new HashSet<>();
	boolean sortable;
	ModelImpl ofModel;
	Class<? extends PropConverter<?>> converter;
	List<CtnPropImpl> childProps;
	
	JoinPropCtn ofCtn;
	CtnField ctnField;
	
	JoinPropImpl(CtnPropBuilder cpBuilder,ModelImpl ofModel,JoinPropCtnImpl ofCtn,
		CtnField ctnField){
		CtnPropBuilder.instanceJoinProp(cpBuilder,this,ofModel,ofCtn,ctnField);
	}
	
	@Override
	public String propName() {
		return propName;
	}

	@Override
	public boolean single() {
		return single;
	}
	
	@Override
	public boolean support(CmpOpr symbol) {
		// 永远支持AND | OR
		if(symbol == CmpOpr.AND || symbol == CmpOpr.OR) {
			return true;
		}
		
		for (SupportCondition supportCondition : supportConditions) {
			if(supportCondition.support(symbol)) {
				return true;
			}
		}
		
		return false;
	}

	@Override
	public boolean sortable() {
		return sortable;
	}

	@Override
	public Model ofModel() {
		return ofModel;
	}

	@Override
	public JoinPropCtn ofCtn() {
		return ofCtn;
	}
	
	@Override
	public List<FieldProp> childProps() {
		return new ArrayList<>(childProps);
	}
	
	@Override
	public boolean isChildPropsEmpty() {
		return childProps.isEmpty();
	}

	@Override
	public CtnProp getChildPropByName(String propName) {
		if(StrUtil.isBlank(propName)) {
			return null;
		}
		
		return CollectionUtils.findOne(childProps, cp -> {
			return cp.propName.equals(propName);
		});
	}
	
	@Override
	public Class<? extends PropConverter<?>> converter() {
		return converter;
	}

	@Override
	public CtnField ctnField() {
		return ctnField;
	}

}
